package com.xianyun.common.security.common;

import com.xianyun.common.core.domain.TokenContent;
import com.xianyun.common.core.exception.token.TokenNotCorrectException;
import com.xianyun.common.core.exception.token.TokenNotExistException;
import com.xianyun.common.core.utils.TokenContentUtil;
import com.xianyun.common.redis.service.RedisService;
import com.xianyun.common.security.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author mac_zyj
 */
@Component
public class TokenConfig {
    @Autowired
    private TokenUserProperties tokenUserProperties;

    @Autowired
    private RedisService redisService;

    public TokenContent checkToken(String token,String sessionId,String model, boolean checkNull) {
        TokenContent resultContent = null;
        try {
            TokenContent tokenContent = JwtUtil.getTokenSignOut(token, TokenContent.class, tokenUserProperties.getJwtSecretKey());
            if (null != tokenContent) {
                System.out.println(tokenContent);
                Object result = redisService.getCacheObject(TokenContentUtil.getRedisSecurityKey(tokenContent.getSessionId()));
                if (null != result && token.equals(result.toString())) {
                    resultContent = tokenContent;
                }
                if (null == resultContent && checkNull) {
                    throw new TokenNotExistException("请检查Token是否过期!");
                }
            }

        } catch (TokenNotExistException ex) {
            if (checkNull) {
                throw new TokenNotCorrectException(model);
            }
        }
        return resultContent;
    }
}